# coding: utf-8
from pathlib import Path
from typing import List

from PySide6.QtCore import Signal, Qt
from PySide6.QtGui import QColor
from PySide6.QtWidgets import QWidget, QHBoxLayout, QVBoxLayout, QFileDialog
from qfluentwidgets import HeaderCardWidget, FluentIcon, LineEdit, BodyLabel
from qfluentwidgets.components.widgets.card_widget import CardSeparator

from ..dialog import InputDialog
from ..widgets import ToolTipButton, CustomBodyLabel


class GroupCardItem(QWidget):
    deleteSignal = Signal(object)

    def __init__(self, parent=None):
        super().__init__(parent)
        self.vBoxLayout = QVBoxLayout(self)
        self.hBoxLayout = QHBoxLayout()
        self.viewLayout = QHBoxLayout()

        self.deleteBtn = ToolTipButton.transparentToolButton(self, FluentIcon.DELETE, '删除')

        self.separator = CardSeparator()
        self.__initWidget()

    def __initWidget(self):
        self.separator.hide()
        self.setFixedHeight(50)

        self.vBoxLayout.setSpacing(0)
        self.vBoxLayout.setContentsMargins(0, 0, 0, 0)
        self.vBoxLayout.addLayout(self.hBoxLayout)
        self.vBoxLayout.addWidget(self.separator)

        self.hBoxLayout.setSpacing(15)
        self.hBoxLayout.setContentsMargins(24, 10, 24, 10)
        self.hBoxLayout.addLayout(self.viewLayout, 1)
        self.hBoxLayout.addWidget(self.deleteBtn, 0, Qt.AlignRight)

        self.deleteBtn.clicked.connect(lambda _: self.deleteSignal.emit(self))

    def setSeparatorVisible(self, isVisible: bool):
        self.separator.setVisible(isVisible)

    def isSeparatorVisible(self):
        return self.separator.isVisible()


class FileGroupCardItem(GroupCardItem):

    def __init__(self, file: str, parent=None):
        super().__init__(parent)
        self.sourceLabel = CustomBodyLabel(self)
        self.descriptionEdit = LineEdit(self)

        filePath = Path(file)
        self.sourceLabel.setText(filePath.as_posix())

        if filePath.is_dir():
            self.descriptionEdit.setText(filePath.name + '/')
        else:
            self.descriptionEdit.setText('.')

        self.viewLayout.addWidget(self.sourceLabel)
        self.viewLayout.addWidget(self.descriptionEdit)


class LabelGroupCardItem(GroupCardItem):

    def __init__(self, text: str, parent=None):
        super().__init__(parent)
        self.sourceLabel = BodyLabel(text, self)
        self.viewLayout.addWidget(self.sourceLabel)

    def setText(self, text: str):
        self.sourceLabel.setText(text)

    def text(self) -> str:
        return self.sourceLabel.text()


class HeaderCardListWidget(HeaderCardWidget):
    def _postInit(self):
        self.items = []  # type: List[GroupCardItem]
        self.itemLayout = QVBoxLayout()

        self.setBorderRadius(5)

        self.itemLayout.setAlignment(Qt.AlignmentFlag.AlignTop)
        self.itemLayout.setSpacing(0)
        self.itemLayout.setContentsMargins(0, 0, 0, 0)
        self.viewLayout.setContentsMargins(0, 0, 0, 0)
        self.viewLayout.addLayout(self.itemLayout)

    def addItem(self, item: GroupCardItem) -> GroupCardItem:
        item.deleteSignal.connect(self.removeItem)

        if self.items:
            self.items[-1].setSeparatorVisible(True)

        self.itemLayout.addWidget(item)
        self.items.append(item)
        return item

    def removeItem(self, item: GroupCardItem):
        self.itemLayout.removeWidget(item)
        self.items.remove(item)
        item.deleteLater()
        if self.items:
            self.items[-1].setSeparatorVisible(True)


class FileGroupCard(HeaderCardListWidget):
    def _postInit(self):
        super()._postInit()
        self.addFileBtn = ToolTipButton.transparentToolButton(self, FluentIcon.ADD, '添加附件')
        self.addFolderBtn = ToolTipButton.transparentToolButton(self, FluentIcon.FOLDER_ADD, '添加文件夹')
        self.hintLabel = BodyLabel('如果要将文件放到根目录中，请在目标目录中输入句点(.)', self)

        self.setTitle('附加文件')
        self.hintLabel.setTextColor(QColor(150, 150, 150), QColor(200, 200, 200))
        self.hintLabel.setContentsMargins(24, 10, 24, 10)

        self.headerLayout.addWidget(self.addFileBtn)
        self.headerLayout.addWidget(self.addFolderBtn)
        self.itemLayout.addWidget(self.hintLabel)

        self.addFileBtn.clicked.connect(self.__onAddFileBtnClicked)
        self.addFolderBtn.clicked.connect(self.__onAddFolderBtnClicked)

    def addGroup(self, file: str) -> FileGroupCardItem:
        group = FileGroupCardItem(file, self)
        self.addItem(group)
        return group

    def __onAddFileBtnClicked(self):
        fileNames, _ = QFileDialog.getOpenFileNames(self, '选择文件', '', 'All Files (*)')
        if not fileNames:
            return
        for fileName in fileNames:
            self.addGroup(fileName)

    def __onAddFolderBtnClicked(self):
        folderName = QFileDialog.getExistingDirectory(self, '选择文件夹', '')
        if not folderName:
            return
        self.addGroup(folderName)


class ListGroupCard(HeaderCardListWidget):
    def _postInit(self):
        super()._postInit()
        self.setTitle('隐式导入')
        self.addBtn = ToolTipButton.transparentToolButton(self, FluentIcon.ADD, '添加')

        self.headerLayout.addWidget(self.addBtn)

        self.addBtn.clicked.connect(self.__onAddBtnClicked)

    def addLabel(self, text: str) -> LabelGroupCardItem:
        group = LabelGroupCardItem(text, self)
        self.addItem(group)
        return group

    def addLabels(self, texts: List[str]) -> List[LabelGroupCardItem]:
        groups = []
        for text in texts:
            group = self.addLabel(text)
            groups.append(group)
        return groups

    def __onAddBtnClicked(self):
        dialog = InputDialog('Python包名', self.window())
        dialog.setPlaceholderText('请输入Python包名，多个包名使用英文逗号隔开')
        if dialog.exec():
            text = dialog.text()
            pkgs = text.split(',')
            self.addLabels(pkgs)
